package com.zdlee.netty.server20.server.handler;

import com.zdlee.netty.server20.protocol.request.ListGroupMembersRequestPacket;
import com.zdlee.netty.server20.protocol.response.ListGroupMembersResponsePacket;
import com.zdlee.netty.server20.session.Session;
import com.zdlee.netty.server20.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zdlee
 * @description: ${DESCRIPTION}
 * @create 2018-12-01 16:03
 */
@ChannelHandler.Sharable
public class ListGroupMembersRequestHandler extends SimpleChannelInboundHandler<ListGroupMembersRequestPacket> {

    public static final ListGroupMembersRequestHandler INSTANCE = new ListGroupMembersRequestHandler();

    private ListGroupMembersRequestHandler() {

    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ListGroupMembersRequestPacket msg) throws Exception {
        //1.获取群的ChannelGroup
        String groupId=msg.getGroupId();
        System.out.println("groupId为%s"+groupId);
        ChannelGroup channelGroup= SessionUtil.getChannelGroup(groupId);


        // 2. 遍历群成员的 channel，对应的 session，构造群成员的信息
        List<Session> sessions=new ArrayList<>();
        for(Channel channel:channelGroup){
            Session session= SessionUtil.getSession(channel);
            sessions.add(session);
        }
        // 3. 构建获取成员列表响应写回到客户端
        ListGroupMembersResponsePacket responsePacket=new ListGroupMembersResponsePacket();


        responsePacket.setGroupId(groupId);
        responsePacket.setSessionList(sessions);
        ctx.channel().writeAndFlush(responsePacket);


    }
}
